package com.svse.component;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 * @Copyright 上海危网信息科技有限公司版权所有
 * @company wwsoft
 * @Date 2019/11/21 15:52
 */
@RestControllerAdvice(basePackages = {"com.svse.controller"})
public class GlobalExceptionHandler {
    /**
     * 全局处理RuntimeException
     * @param handlerMethod
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public String handlerRuntimeExcepetion(HandlerMethod handlerMethod, Exception e) {
        Exception exception = (Exception) e;
        int status = HttpStatus.BAD_REQUEST.value();
        return "{\"code\":" + status + ",\"message\":\"" + exception.getMessage() + "\",\"className\":\"" + handlerMethod.getBean().getClass() + "\",\"methodName\":\"" + handlerMethod.getMethod().getName() + "\"}";
    }

    /**
     * 全局处理Exception
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public String handlerExcepetion(Exception e) {
        Exception exception = (Exception) e;
        int status = HttpStatus.INTERNAL_SERVER_ERROR.value();
        if (e instanceof NoHandlerFoundException) {
            status = HttpStatus.NOT_FOUND.value();
        }
        return "{\"code\":" + status + ",\"message\":\"" + exception.getMessage() + "\"}";
    }
}
